package com.kfgj.hkp.common.components.xml;

import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

public class XmlTransformUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(XmlTransformUtil.class);

	public static String obj2xml(Object obj) {

		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			StringWriter sw = new StringWriter();
			Marshaller marshaller = context.createMarshaller();
			//表示不需要生成XML头，比如<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			//表示需要格式化输出
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
			marshaller.marshal(obj, sw);
			sw.flush();
			return sw.toString();
		} catch (JAXBException e) {
			logger.error("error when obj2xml", e);
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public static Object xml2obj(String xml, Class cls) {

		try {
			JAXBContext context = JAXBContext.newInstance(cls);
			StringReader sr = new StringReader(xml);
			Object obj = context.createUnmarshaller().unmarshal(sr);
			sr.close();
			return obj;
		} catch (JAXBException e) {
			logger.error(String.format("error when xml2obj {%s}",xml), e);
		} catch (Exception e) {
			logger.error(String.format("error when xml2obj {%s}",xml), e);
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public static Object xml2obj(InputStream xml, Class cls) {

		try {
			JAXBContext context = JAXBContext.newInstance(cls);
			Object obj = context.createUnmarshaller().unmarshal(xml);
			xml.close();
			return obj;
		} catch (JAXBException e) {
			logger.error("error when xml2obj", e);
		} catch (Exception e) {
			logger.error("error when xml2obj", e);
		}
		return null;
	}

}
